package com.weblog.weblog.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weblog.weblog.admin.model.vo.tag.*;
import com.weblog.weblog.admin.service.AdminTagService;
import com.weblog.weblog.common.domain.dos.ArticleTagRelDO;
import com.weblog.weblog.common.domain.dos.TagDO;
import com.weblog.weblog.common.domain.mapper.ArticleTagRelMapper;
import com.weblog.weblog.common.domain.mapper.TagMapper;
import com.weblog.weblog.common.enums.ResponseCodeEnum;
import com.weblog.weblog.common.exception.BizException;
import com.weblog.weblog.common.modul.vo.SelectRspVO;
import com.weblog.weblog.common.utils.PageResponse;
import com.weblog.weblog.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author gc
 * @date 2023年09月28日 13:05
 */
@Service
@Slf4j
public class AdminTagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements AdminTagService {

    private final TagMapper tagMapper;

    private final ArticleTagRelMapper articleTagRelMapper;

    public AdminTagServiceImpl(TagMapper tagMapper, ArticleTagRelMapper articleTagRelMapper) {
        this.tagMapper = tagMapper;
        this.articleTagRelMapper = articleTagRelMapper;
    }

    @Override
    public Response addTag(AddTagRsqVO addTagRsqVO) {
        List<TagDO> tagDOS = addTagRsqVO.getTags()
                .stream().map(tagName -> TagDO.builder()
                        .name(tagName.trim())
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build()
                ).collect(Collectors.toList());
        try {
            saveBatch(tagDOS);
        } catch (Exception e) {
            log.warn("改标签已存在",e);
        }
        return Response.success();
    }

    @Override
    public PageResponse findTagPageList(FindTagPageListReqVO findTagPageListReqVO) {
        //获取当前页
        Long current = findTagPageListReqVO.getCurrent();
        Long size = findTagPageListReqVO.getSize();
        String name = findTagPageListReqVO.getName();
        LocalDate startDate = findTagPageListReqVO.getStartDate();
        LocalDate endDate = findTagPageListReqVO.getEndDate();

        Page<TagDO> page = tagMapper.selectPageList(current, size, name, startDate, endDate);

        List<TagDO> records = page.getRecords();

        //do转vo
        List<FindTagPageListRspVO> vos = null;
        if(!CollectionUtils.isEmpty(records)){
            vos =records.stream().map(tagDO -> FindTagPageListRspVO.builder()
                            .id(tagDO.getId())
                            .name(tagDO.getName())
                            .createTime(tagDO.getCreateTime())
                            .articlesTotal(tagDO.getArticlesTotal())
                            .build()).collect(Collectors.toList());

        }
        return PageResponse.success(page,vos);
    }

    @Override
    public Response deleteTag(DeleteTagReqVO deleteTagReqVO) {
        Long tagID = deleteTagReqVO.getId();

        //校验是否有关联文章
        ArticleTagRelDO articleTagRelDO = articleTagRelMapper.selectOneById(tagID);

        if(Objects.nonNull(articleTagRelDO)){
            log.warn("==> 此标签下包含文章，无法删除，tagId: {}", tagID);
            throw new BizException(ResponseCodeEnum.TAG_CAN_NOT_DELETE);
        }

        int i = tagMapper.deleteById(tagID);

        return i == 1 ? Response.success() : Response.fail(ResponseCodeEnum.TAG_NOT_EXISTED);
    }

    @Override
    public Response searchTag(SearchTagReqVO searchTagReqVO) {
        String key = searchTagReqVO.getKey();

        List<TagDO> tagDOS = tagMapper.selectByKey(key);

        //do转vo
        List<SelectRspVO> vos = null;

        if(!CollectionUtils.isEmpty(tagDOS)){
            vos = tagDOS.stream()
                    .map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }
        return Response.success(vos);
    }

    @Override
    public Response findTagSelectList() {
        //查询所有标签
        List<TagDO> tagDOS = tagMapper.selectList(Wrappers.emptyWrapper());

        //DO -> VO

        List<SelectRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOS)){
            vos = tagDOS.stream()
                    .map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }
        return Response.success(vos);
    }
}
